package hive.function;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

/**
 * 输入一个字符串，返回当前字符串的长度
 */
public class Demo01_getStrBackLen extends GenericUDF {
    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        //如果参数的个数不是1(逻辑中要求必须是1) 人为抛出异常
        if(arguments.length != 1){
            throw new UDFArgumentLengthException("Input Args Length Error !!!");
        }

        //如果参数的类型符合要求(根据实际情况确定)
        if(!arguments[0].getCategory().equals(ObjectInspector.Category.PRIMITIVE)){
            throw new UDFArgumentTypeException(0,"Input Args Type Error !!!");
        }

        //确认业务逻辑中的返回值类型为java的普通类型 int
        return PrimitiveObjectInspectorFactory.javaIntObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException {

        //如果字符串为空，返回长度为0
        if(arguments[0].get()==null){
            return 0;
        }

        //如果字符串不为空，返回正常的长度
        return arguments[0].get().toString().length();
    }

    @Override
    public String getDisplayString(String[] children) {
        return "";
    }
}
